package teacher;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.util.LinkedHashMap;
import java.util.Map;

@WebServlet("/ProfileUpdateServlet")
public class ProfileUpdateServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8"); // 添加字符编码设置
        HttpSession session = request.getSession(false); // 不创建新会话
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> jsonResponse = new LinkedHashMap<>();

        // 会话验证
        if (session == null || session.getAttribute("teacher_id") == null) {
            jsonResponse.put("success", false);
            jsonResponse.put("code", 401);
            jsonResponse.put("message", "会话已过期，请重新登录");
            out.print(mapToJson(jsonResponse));
            return;
        }

        Integer teacherId = (Integer) session.getAttribute("teacher_id");
        String title = request.getParameter("title");
        String phone = request.getParameter("phone");
        String email = request.getParameter("email");

        // 调试输出
        System.out.println("更新个人信息 - 参数: " +
                "title=" + title + ", phone=" + phone + ", email=" + email);

        Connectmysql conn = null;
        try {
            conn = new Connectmysql(
                    "jdbc:mysql://localhost:3306/exam",
                    "root",
                    "root",
                    "com.mysql.cj.jdbc.Driver"
            );

            if (conn.open()) {
                String sql = "UPDATE teacher SET title = ?, phone = ?, email = ? WHERE teacher_id = ?";
                int result = conn.executeSqlUpdate(sql, new Object[]{title, phone, email, teacherId});

                if (result > 0) {
                    // 更新 session 中的信息
                    session.setAttribute("title", title);
                    session.setAttribute("phone", phone);
                    session.setAttribute("email", email);

                    // 重新查询基本的教师信息
                    String selectSql = "SELECT teacher_no, name FROM teacher WHERE teacher_id = ?";
                    ResultSet rs = conn.executeSql(selectSql, new Object[]{teacherId});

                    if (rs.next()) {
                        jsonResponse.put("success", true);
                        jsonResponse.put("code", 200);
                        jsonResponse.put("message", "个人信息更新成功");
                        jsonResponse.put("teacher_id", teacherId.toString());
                        jsonResponse.put("teacher_no", rs.getString("teacher_no"));
                        jsonResponse.put("teacher_name", rs.getString("name"));
                        jsonResponse.put("title", title);
                        jsonResponse.put("phone", phone);
                        jsonResponse.put("email", email);

                        // 调试日志
                        System.out.println("个人信息更新成功: " + jsonResponse);
                    } else {
                        jsonResponse.put("success", false);
                        jsonResponse.put("code", 404);
                        jsonResponse.put("message", "未找到教师信息");
                    }
                } else {
                    jsonResponse.put("success", false);
                    jsonResponse.put("code", 404);
                    jsonResponse.put("message", "个人信息更新失败，数据库无变化");
                }
            } else {
                jsonResponse.put("success", false);
                jsonResponse.put("code", 500);
                jsonResponse.put("message", "数据库连接失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonResponse.put("success", false);
            jsonResponse.put("code", 500);
            jsonResponse.put("message", "数据库错误: " + e.getMessage());
        } finally {
            if (conn != null) {
                conn.close();
            }
            out.print(mapToJson(jsonResponse));
            out.flush();
        }
    }

    // 将 Map 转换为 JSON 字符串
    private String mapToJson(Map<String, Object> map) {
        StringBuilder json = new StringBuilder("{");
        boolean first = true;

        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (!first) {
                json.append(",");
            }
            first = false;

            json.append("\"")
                    .append(escapeJson(entry.getKey()))
                    .append("\":");

            Object value = entry.getValue();
            if (value instanceof String) {
                json.append("\"")
                        .append(escapeJson((String) value))
                        .append("\"");
            } else if (value instanceof Boolean) {
                json.append(value);
            } else {
                json.append("\"")
                        .append(value)
                        .append("\"");
            }
        }

        json.append("}");
        return json.toString();
    }

    // 转义 JSON 特殊字符
    private String escapeJson(String input) {
        if (input == null) return "";
        return input.replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\b", "\\b")
                .replace("\f", "\\f")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t");
    }
}